package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserService userService; //依赖注入 用户
    @Autowired
    private AddressBookService addressBookService; //依赖注入地址簿
    @Autowired
    private ShoppingCartService shoppingCartService; //依赖注入购物车
    @Autowired
    private OrderDetailService orderDetailService; //依赖注入订单明细表

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 下单
     *
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //获取购物车信息
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId, userId).list();
        //根据用户id获取用户信息
        User user = userService.getById(userId);
        //根据地址id查询地址数据
        AddressBook addressBooks = addressBookService.getById(orders.getAddressBookId());
        //生成订单id(调用工具类生成雪花算法)
        long orderId = IdWorker.getId();
        //定义订单总金额
        BigDecimal total = new BigDecimal(0);

        //1.添加订单明细 order_detail 表中添加数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        //TODO 补全OrderDetail对象的数据
        for (ShoppingCart cart : shoppingCartList) {
            //创建一个订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            //设置订单id
            orderDetail.setOrderId(orderId);
            //设置名称
            orderDetail.setName(cart.getName());
            //设置菜品id
            orderDetail.setDishId(cart.getDishId());
            //设置套餐id
            orderDetail.setSetmealId(cart.getSetmealId());
            //设置口味
            orderDetail.setDishFlavor(cart.getDishFlavor());
            //设置数量
            orderDetail.setNumber(cart.getNumber());
            //设置图片
            orderDetail.setImage(cart.getImage());
            //设置金额
            orderDetail.setAmount(cart.getAmount());
            //计算总金额
            BigDecimal multiply = orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber()));
            //将计算后的金额重新赋值
            total = total.add(multiply);
            //TODO 往集合里添加orderDetail对象
            orderDetails.add(orderDetail);
        }
        //调用添加集合方法往订单明细表添加数据
        orderDetailService.saveBatch(orderDetails);

        //2.添加订单数据 orders 表中添加数据
        //TODO 补全orders对象的数据
        //设置订单id
        orders.setId(orderId);
        //设置订单号
        orders.setNumber(String.valueOf(orderId));
        //设置订单状态
        orders.setStatus(2);
        //设置下单用户id
        orders.setUserId(userId);
        //设置地址
        orders.setAddressBookId(addressBooks.getId());
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置用户名
        orders.setUserName(user.getName());
        //设置手机号
        orders.setPhone(addressBooks.getPhone());
        //设置地址
        orders.setAddress(addressBooks.getDetail());
        //设置收货人
        orders.setConsignee(addressBooks.getConsignee());
        //设置金额
        orders.setAmount(total);
        //添加数据
        this.save(orders);
        //清空购物车
        shoppingCartService.lambdaUpdate().eq(ShoppingCart::getUserId, userId).remove();
    }

    /**
     * 自定义订单分页查询
     */
    @Override
    public Page<OrdersDto> selectPage(Integer page, Integer pageSize) {
        Page<OrdersDto> pageInfo = new Page<>(page, pageSize);
        return ordersMapper.selectByPage(pageInfo);
    }

    /**
     * 客户端带条件分页查询
     */
    @Override
    public Page<OrdersDto> selectByPage(Integer page, Integer pageSize, String number, LocalDateTime beginTime, LocalDateTime endTime) {
        Page<OrdersDto> pageInfo = new Page<>(page, pageSize);
        return ordersMapper.getByPage(pageInfo, number, beginTime, endTime);
    }

    @Override
    public void add(Orders orders) {
        //获取订单号
        Long orderId = orders.getId();
        //根据订单号查询订单明细表
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
        //创建一个集合用于存储购物车对象
        ArrayList<ShoppingCart> shoppingCarts = new ArrayList<>();
        //遍历订单明细表集合
        for (OrderDetail orderDetail : orderDetailList) {
            //创建一个购物车对象
            ShoppingCart cart = new ShoppingCart();
            //设置名称
            cart.setName(orderDetail.getName());
            //设置用户id 从线程中获取
            cart.setUserId(BaseContext.getCurrentId());
            //设置菜品id
            cart.setDishId(orderDetail.getDishId());
            //设置套餐id
            cart.setSetmealId(orderDetail.getSetmealId());
            //设置口味
            cart.setDishFlavor(orderDetail.getDishFlavor());
            //设置数量
            cart.setNumber(orderDetail.getNumber());
            //设置金额
            cart.setAmount(orderDetail.getAmount());
            //设置图片
            cart.setImage(orderDetail.getImage());
            //将对象添加到集合中
            shoppingCarts.add(cart);
        }
        //调用方法添加数据
        shoppingCartService.saveBatch(shoppingCarts);

    }
}
